# Maintainer: umarcor <unai.martinezcorral@ehu.eus>

_realname=prjtrellis
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.4
pkgrel=3
pkgdesc="Documenting the Lattice ECP5 bit-stream format (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64' 'clang32')
url="https://github.com/YosysHQ/prjtrellis"
license=('spdx:MIT')
groups=("${MINGW_PACKAGE_PREFIX}-eda")
depends=(
  "${MINGW_PACKAGE_PREFIX}-boost"
  $([[ ${MSYSTEM} == MINGW32 ]] || echo "${MINGW_PACKAGE_PREFIX}-python")  # memory footprint of cc1plus is too large for mingw32
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "git"
)

_commit_db='35d900a94ff0db152679a67bf6e4fbf40ebc34aa'

source=("${_realname}-${pkgver}.tar.gz"::"https://github.com/YosysHQ/prjtrellis/archive/refs/tags/${pkgver}.tar.gz"
        "${_realname}-db"::"git+https://github.com/YosysHQ/prjtrellis-db.git#commit=${_commit_db}")
sha256sums=('46fe9d98676953e0cccf1d6332755d217a0861e420f1a12dabfda74d81ccc147'
            'SKIP')

prepare () {
  cd "${srcdir}/${_realname}-db"
  cp -r * "${srcdir}/${_realname}-${pkgver}/database/"
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  local -a _extra_config
  if check_option "debug" "y"; then
    _extra_config+=(-DCMAKE_BUILD_TYPE=Debug)
  else
    _extra_config+=(-DCMAKE_BUILD_TYPE=Release)
  fi

  if [[ ${MSYSTEM} == MINGW32 ]]; then
    _extra_config+=("-DBUILD_PYTHON=OFF")
  else
    _pyver=$(${MINGW_PREFIX}/bin/python -c "import sys;sys.stdout.write('.'.join(map(str, sys.version_info[:2])))")
    _extra_config+=("-DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python" "-DPython3_LIBRARY=${MINGW_PREFIX}/lib/libpython${_pyver}.dll.a")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_PREFIX_PATH="${MINGW_PREFIX}" \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      ../${_realname}-${pkgver}/libtrellis

  "${MINGW_PREFIX}"/bin/cmake.exe --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  for item in ecpbram ecpmulti ecppack ecppll ecpunpack; do
    msg2 "Check $item"
    ./"$item" --help
  done
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .

  install -Dm644 "${srcdir}/${_realname}-${pkgver}"/COPYING "${pkgdir}${MINGW_PREFIX}"/share/licenses/${_realname}/LICENSE
}
